<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="店铺名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="店铺名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="营业状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择营业状态" style="width: 150px">
            <el-option :key="ShopStatusEnum.OPEN" :value="ShopStatusEnum.OPEN" label="营业中" />
            <el-option :key="ShopStatusEnum.REST" :value="ShopStatusEnum.REST" label="休息中" />
            <el-option :key="ShopStatusEnum.CLOSE" :value="ShopStatusEnum.CLOSE" label="已打烊" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['biz:shop:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['biz:shop:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column
          key="userId"
          label="关联商家"
          prop="userId"
          min-width="150"
          align="center"
        />
        <el-table-column key="name" label="店铺名称" prop="name" min-width="150" align="center" />
        <el-table-column key="status" label="营业状态" prop="status" min-width="150" align="center">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === ShopStatusEnum.OPEN
                  ? 'success'
                  : scope.row.status === ShopStatusEnum.REST
                    ? 'warning'
                    : 'danger'
              "
            >
              {{
                scope.row.status === ShopStatusEnum.OPEN
                  ? "营业中"
                  : scope.row.status === ShopStatusEnum.REST
                    ? "休息中"
                    : "已打烊"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="logo" label="店铺LOGO" prop="logo" min-width="150" align="center" />
        <el-table-column
          key="description"
          label="店铺描述"
          prop="description"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="address"
          label="店铺详细地址"
          prop="address"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="longitude"
          label="经度"
          prop="longitude"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="latitude"
          label="纬度"
          prop="latitude"
          min-width="150"
          align="center"
        />
        <el-table-column key="phone" label="手机号" prop="phone" min-width="150" align="center" />
        <el-table-column
          key="businessHours"
          label="营业时间"
          prop="businessHours"
          min-width="150"
          align="center"
        />

        <el-table-column
          key="deliveryFee"
          label="配送费"
          prop="deliveryFee"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="minOrderAmount"
          label="起送金额"
          prop="minOrderAmount"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['biz:shop:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['biz:shop:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 店铺管理表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="关联商家" prop="userId">
          <el-input v-model="formData.userId" placeholder="关联商家用户ID" disabled="true" />
        </el-form-item>

        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="formData.name" placeholder="店铺名称" />
        </el-form-item>

        <el-form-item label="店铺LOGO" prop="logo">
          <el-input v-model="formData.logo" placeholder="店铺LOGO" />
        </el-form-item>

        <el-form-item label="店铺描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="店铺描述" />
        </el-form-item>

        <el-form-item label="店铺详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="店铺详细地址" />
        </el-form-item>

        <el-form-item label="经度" prop="longitude">
          <el-input v-model="formData.longitude" placeholder="经度" />
        </el-form-item>

        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="formData.latitude" placeholder="纬度" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="手机号" />
        </el-form-item>

        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="formData.businessHours" placeholder="营业时间，如09:00-21:00" />
        </el-form-item>

        <el-form-item label="营业状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择营业状态">
            <el-option :value="ShopStatusEnum.OPEN" label="营业中" />
            <el-option :value="ShopStatusEnum.REST" label="休息中" />
            <el-option :value="ShopStatusEnum.CLOSE" label="已打烊" />
          </el-select>
        </el-form-item>

        <el-form-item label="配送费" prop="deliveryFee">
          <el-input-number v-model="formData.deliveryFee" placeholder="配送费" />
        </el-form-item>

        <el-form-item label="起送金额" prop="minOrderAmount">
          <el-input-number v-model="formData.minOrderAmount" placeholder="起送金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Shop",
  inheritAttrs: false,
});

import ShopAPI, { ShopPageVO, ShopForm, ShopPageQuery } from "@/api/biz/shop";
import { ShopStatusEnum } from "@/enums/system/shop-status.enum";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ShopPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 店铺管理表格数据
const pageData = ref<ShopPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 店铺管理表单数据
const formData = reactive<ShopForm>({
  id: 1,
});

// 店铺管理表单校验规则
const rules = reactive({
  userId: [{ required: true, message: "请输入关联商家用户ID", trigger: "blur" }],
  name: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
});

/** 查询店铺管理 */
function handleQuery() {
  loading.value = true;
  ShopAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置店铺管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开店铺管理弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改店铺管理";
    ShopAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增店铺管理";
  }
}

/** 提交店铺管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ShopAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ShopAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭店铺管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除店铺管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ShopAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
